using AutoMapper;
using BackData;
using Domain;
using Domain.DTOs.ProcessSteps;
using Domain.工艺工序;
using Infratructure;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Transactions;
using Team.API.Applocation.Command.Makesteps;
using Yitter.IdGenerator;

namespace Team.API.Applocation.Hanldler.Makesteps
{
    /// <summary>
    /// 更新成品工艺工序处理器：负责节点信息维护与审计日志
    /// </summary>
    public class UpdateMakestepHandler : IRequestHandler<UpdateMakestepCommand, APIResult<MakestepListDTO>>
    {
        private readonly IRepository<Makestepmodel> repository;
        private readonly IRepository<Nlogmodel> logRepository;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateMakestepHandler> logger;

        public UpdateMakestepHandler(
            IRepository<Makestepmodel> repository,
            IRepository<Nlogmodel> logRepository,
            IMapper mapper,
            ILogger<UpdateMakestepHandler> logger)
        {
            this.repository = repository;
            this.logRepository = logRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<APIResult<MakestepListDTO>> Handle(UpdateMakestepCommand request, CancellationToken cancellationToken)
        {
            // 1. 校验目标记录
            var entity = await repository.GetByIdAsync(request.Id);
            if (entity == null || entity.Parentid != 0 || entity.IsDel)
            {
                return APIResult<MakestepListDTO>.Faile("记录不存在或已删除");
            }

            var currentUser = string.IsNullOrWhiteSpace(request.CurrentUserName) ? "系统" : request.CurrentUserName;

            entity.Processname = request.Processname;
            entity.Processcode = request.Processcode;
            entity.Processdescription = request.Processdescription;
            entity.Version = request.Version;
            entity.Goodsname = request.Goodsname;
            entity.Deliverables = request.Deliverables;
            entity.Kahuna = request.Kahuna;
            entity.Departmentname = request.Departmentname;
            entity.IsUse = request.IsUse;
            entity.SpanTime = request.SpanTime;
            entity.EquipmentId = request.EquipmentId;

            // 记录修改动作
            var logEntity = new Nlogmodel
            {
                Id = YitIdHelper.NextId(),
                Message = $"{currentUser}修改工艺工序：{entity.Processname}",
                Category = "Process",
                Otherkey = entity.Id,
                Operatingtime = DateTime.Now,
                Operator = currentUser,
                IsDel = false
            };

            // 2. 使用事务保证“工序 + 日志”同时落库
            using var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                var effect = await repository.UpdateAsync(entity);
                if (effect <= 0)
                {
                    logger.LogWarning("[工艺工序-修改] 更新失败，操作人：{User}，工序：{Process}", currentUser, entity.Processname);
                    return APIResult<MakestepListDTO>.Faile("更新失败");
                }

                var logEffect = await logRepository.AddAsync(logEntity);
                if (logEffect <= 0)
                {
                    logger.LogWarning("[工艺工序-修改] 日志写入失败，操作人：{User}，工序：{Process}", currentUser, entity.Processname);
                    return APIResult<MakestepListDTO>.Faile("更新失败：日志写入失败");
                }

                transaction.Complete();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "[工艺工序-修改] 事务执行异常，操作人：{User}", currentUser);
                throw;
            }

            var dto = mapper.Map<MakestepListDTO>(entity);
            return APIResult<MakestepListDTO>.Ok("更新成功", dto);
        }
    }
}

